package com.threeox.commonlibrary.request;

import android.os.Message;

import com.alibaba.fastjson.JSONObject;
import com.threeox.commonlibrary.CommonApplcation;
import com.threeox.commonlibrary.adapter.base.IAdapter;
import com.threeox.commonlibrary.callback.CommonCallback;
import com.threeox.commonlibrary.entity.engine.model.listmodel.ListModelMsg;
import com.threeox.commonlibrary.entity.engine.request.base.BaseRequestMsg;
import com.threeox.commonlibrary.entity.engine.request.sqlite.SqliteRequestMsg;
import com.threeox.commonlibrary.inter.OnRequestListener;
import com.threeox.commonlibrary.ui.view.engineview.listmodel.ListModelBaseView;
import com.threeox.commonlibrary.ui.view.inter.engine.listmodel.IListModelExtend;
import com.threeox.commonlibrary.ui.view.inter.pullrefresh.IPullToRefLayout;
import com.threeox.commonlibrary.util.JSONUtils;
import com.threeox.commonlibrary.util.request.RequestHelper;
import com.threeox.utillibrary.util.EmptyUtils;
import com.threeox.utillibrary.util.HandlerUtils;
import com.threeox.utillibrary.util.HandlerUtils.OnHandlerListener;
import com.threeox.utillibrary.util.LogUtils;
import com.threeox.utillibrary.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @ClassName: CommonRequestUtil
 *
 * @Description: Todo(请求网络的工具类)
 *
 * @author 赵屈犇
 *
 * @date 创建时间:2016/12/22 14:41
 *
 * @version 1.0
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public class CommonRequestUtil implements IRequest, OnHandlerListener, OnRequestListener {

	protected static final String TAG = CommonRequestUtil.class.getName();

    protected List mDatas;
    protected IAdapter mAdapter;

	protected CommonApplcation mApplcation;
    protected ListModelMsg mListModelMessage;
	protected IListModelExtend mOnListModelExtend;
    protected ListModelBaseView mListModelBaseView;
	// protected IReloadView mReloadView;// 各种加载状态的View
	protected boolean mIsClear;// 是否清空数据
	protected int mFirstPage = 0;// 首页
	protected boolean mIsEnd = false;// 是否已经没有数据
	protected int SUCCEED = IPullToRefLayout.SUCCEED;
	protected int FAIL = IPullToRefLayout.FAIL;
	// 默认是第一次进入
	protected boolean mIsFirstJoin = true;

    private HandlerUtils mHandlerUtils;
    private RequestHelper mRequestHelper;

	protected int NODATA = 2;// 没有数据

	public CommonRequestUtil() {
	}

	public CommonRequestUtil(List datas, IAdapter baseAdapter, ListModelMsg listModelMsg) {
		this.mDatas = datas;
		this.mAdapter = baseAdapter;
		this.mListModelMessage = listModelMsg;
		this.mApplcation = CommonApplcation.getInstance();

        mRequestHelper = RequestHelper.newInstance().setOnRequestListener(this);
        mHandlerUtils = HandlerUtils.getInstance().setOnHandlerListener(this);
    }

	public static CommonRequestUtil newInstance(List datas, IAdapter baseAdapter, ListModelMsg listModelMsg) {
		return new CommonRequestUtil(datas, baseAdapter, listModelMsg);
	}

	@Override
	public void execFirst(BaseRequestMsg requestMsg) {
        String pageName = mListModelMessage.getPageName();
        if (requestMsg instanceof SqliteRequestMsg) {// 属于本地SQLITE数据库请求
			if (mListModelMessage.isLimit()) {
				JSONObject requestParam = requestMsg.getRequestParam();
				if (!requestParam.containsKey(SqliteRequestMsg.OFFSET)) {
					requestMsg.putRequestParam(SqliteRequestMsg.OFFSET, 0);
				}
				if (EmptyUtils.isEmpty(pageName)) {
					mListModelMessage.setPageName(SqliteRequestMsg.OFFSET);
				}
			}
        }
        setIsClear(true);
		if (EmptyUtils.isNotEmpty(pageName)) { // 判断是否有pageName
			if (requestMsg instanceof SqliteRequestMsg) {
				mFirstPage = 0;
			}
            JSONUtils.putJSONValue(requestMsg.getRequestParam(), pageName, mFirstPage);
		}
		exec(requestMsg);
	}
    @Override
    public void execNext(BaseRequestMsg requestMsg) {
        String pageName = mListModelMessage.getPageName();
        if (EmptyUtils.isNotEmpty(pageName)) { // 判断是否有pageName
            int pageNum = 0;
            try {
                pageNum = Integer.parseInt(String.valueOf(JSONUtils.getJSONValue(requestMsg.getRequestParam(), pageName)));// 取得当前第几页
                ++pageNum;
            } catch (Exception e) {
                pageNum = -1;
            }
            if (pageNum != -1) {
				JSONUtils.putJSONValue(requestMsg.getRequestParam(), pageName, pageNum);
			}
        }
		exec(requestMsg);
    }

    @Override
    public void exec(BaseRequestMsg requestMsg) {
        if (mIsEnd) {
            mHandlerUtils.putWhat(NODATA).send(500);
            mListModelBaseView.requestSucceed(null);
            return;
        }
        mRequestHelper.execRequest(requestMsg);
    }

	/**
	 * 设置是否请求集合
	 * 
	 * @param mIsClear
	 */
	@Override
	public void setIsClear(boolean mIsClear) {
		this.mIsClear = mIsClear;
		this.mIsEnd = false;
	}

	/**
	 * 设置第一页的
	 * 
	 * @param mFirstPage
	 */
	@Override
	public void setFirstPage(int mFirstPage) {
		this.mFirstPage = mFirstPage;
	}

	/**
	 * 隐藏头部或底部
	 *
	 * @param state
	 * @param msg
	 */
	public void hideHeaderFooter(int state, String msg) {
		if (mListModelBaseView != null) {
			mListModelBaseView.hideHeaderFooter(state, msg);
		}
	}

	@Override
	public void onSuccess(BaseRequestMsg requestMsg, String url, int id, String msg, Object data) {
		if (data == null || data instanceof ArrayList) {
			onSuccess((List) data);
		} else {
            hideHeaderFooter(SUCCEED, "数据加载成功!");
			if (mOnListModelExtend != null) {
				List result = mOnListModelExtend.onParseData(data);
				if (result != null) {
                    onSuccess(result);
					return;
				}
			}
            mListModelBaseView.requestFault(data, "返回数据不是集合,请检查服务器返回数据....");
		}
	}

	@Override
	public void inProgress(BaseRequestMsg requestMsg, float progress, long total, int id, String url) {
		if (mOnListModelExtend != null) {
            mOnListModelExtend.onRequestInProgress(requestMsg, progress, total, id, url);
		}
	}

	@Override
	public void onError(BaseRequestMsg requestMsg, String url, int id, Object code, String msg, Object data) {
		if (RequestHelper.NOTNETWORKCONNECTED.equals(String.valueOf(code))) {
            mListModelBaseView.networkClose(mListModelMessage.getNotNetWorkMessage());
		} else if (CommonCallback.NOTDATAERRORCODE.equals(String.valueOf(code))) {
			mListModelBaseView.notData(msg);
		} else {
			msg = mListModelBaseView.requestFault(code, msg);
		}
		onError(msg);
		if (mOnListModelExtend != null) {
			mOnListModelExtend.onRequestError(requestMsg, url, id, code, msg);
		}
	}

	/**
	 * 请求正确的处理
	 *
	 * @param datas
	 */
	protected void onSuccess(List datas) {
		try {
			LogUtils.d(TAG, "进入了:"+System.currentTimeMillis());
			boolean isFirst = false;
			if (mOnListModelExtend != null && !mOnListModelExtend.onBeforeParseData(datas)) {
				return;
			}
			if (EmptyUtils.isNotEmpty(datas)) {// 有数据的情况下
				if (mIsClear) {// 需要清空
					isFirst = true;
					mDatas.clear();
					setIsClear(false);
					mListModelBaseView.smoothScrollToPosition(0);
				}
				mAdapter.addAll(datas);
                mListModelBaseView.requestSucceed(datas);
			} else {// 沒有数据的情况下
				if (mIsClear) {// 需要清空
					isFirst = true;
					mAdapter.removeAll();
					setIsClear(false);
                    mListModelBaseView.smoothScrollToPosition(0);
				}
				mIsEnd = true;
                if (EmptyUtils.isEmpty(mDatas)) {
                    mListModelBaseView.notData(mListModelMessage.getNotDataMessage());
                } else {
                    mListModelBaseView.requestSucceed(datas);
				}
			}
			if (mOnListModelExtend != null) {
				mOnListModelExtend.onAfterParseData(isFirst, datas);
			}
			if (mListModelMessage.isCalcHig()) {
				// BaseUtils.setListViewAutoHig((ListView) mPullToRefLayout.getMainView());
			}
            mListModelBaseView.expandAllExpandable();
		} catch (Exception e) {
			LogUtils.e("onSuccess" + e.getMessage());
		} finally {
			hideHeaderFooter(SUCCEED, "数据加载成功!");
		}
		LogUtils.d(TAG, "结束了:"+System.currentTimeMillis());
	}

	/**
	 * 请求错误的处理
	 *
	 * @param msg
	 */
	protected void onError(String msg) {
		if (mListModelMessage.isShowErrorToast()) {
			ToastUtils.showLongToastSafe(mApplcation, msg);
		}
		hideHeaderFooter(FAIL, msg);
	}


    @Override
    public void setListModelBaseView(ListModelBaseView listModelBaseView) {
        this.mListModelBaseView = listModelBaseView;
        this.mOnListModelExtend = listModelBaseView.getListModelExtend();
		mRequestHelper.setIntent(mListModelBaseView.getIntent());
    }

    @Override
	public void onHandleMessage(Message msg) {
		try {
			int what = msg.what;
			if (NODATA == what) {
				hideHeaderFooter(FAIL, "没有更多数据了...");
			}
		} catch (Exception e) {
			onError(e.getMessage());
		}
	}

	@Override
	public void setFirstJoin(boolean isFirstJoin) {
		this.mIsFirstJoin = isFirstJoin;
	}

}
